package com.logistics.service.impl;

import com.logistics.common.Result;
import com.logistics.entity.LogisticsOrder;
import com.logistics.mapper.LogisticsOrderMapper;
import com.logistics.service.LogisticsOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class LogisticsOrderServiceImpl implements LogisticsOrderService {
    @Autowired
    private LogisticsOrderMapper logisticsOrderMapper;

    @Override
    @Transactional
    public Result<LogisticsOrder> createOrder(LogisticsOrder order) {
        try {
            // 参数验证
            if (order.getUserId() == null) {
                return Result.fail("用户ID不能为空");
            }
            if (StringUtils.isEmpty(order.getOrderNo())) {
                return Result.fail("订单号不能为空");
            }
            if (StringUtils.isEmpty(order.getSenderName())) {
                return Result.fail("发件人姓名不能为空");
            }
            if (StringUtils.isEmpty(order.getSenderPhone())) {
                return Result.fail("发件人电话不能为空");
            }
            if (StringUtils.isEmpty(order.getReceiverName())) {
                return Result.fail("收件人姓名不能为空");
            }
            if (StringUtils.isEmpty(order.getReceiverPhone())) {
                return Result.fail("收件人电话不能为空");
            }
            if (StringUtils.isEmpty(order.getReceiverAddress())) {
                return Result.fail("收件地址不能为空");
            }

            // 设置默认值
            if (order.getStatus() == null) {
                order.setStatus(0); // 默认状态为待处理
            }
            if (order.getGoodsType() == null) {
                order.setGoodsType("普通货物");
            }
            if (order.getGoodsWeight() == null) {
                order.setGoodsWeight(new BigDecimal("0"));
            }
            if (order.getGoodsVolume() == null) {
                order.setGoodsVolume(new BigDecimal("0"));
            }

            logisticsOrderMapper.insert(order);
            return Result.success();
        } catch (Exception e) {
            log.error("创建订单失败", e);
            return Result.fail("创建订单失败：" + e.getMessage());
        }
    }

    @Override
    public Result<LogisticsOrder> getOrder(Long id) {
        try {
            LogisticsOrder order = logisticsOrderMapper.selectById(id);
            if (order == null) {
                return Result.error("订单不存在");
            }
            return Result.success(order);
        } catch (Exception e) {
            return Result.error("获取订单失败：" + e.getMessage());
        }
    }

    @Override
    public Result<LogisticsOrder> getOrderByOrderNo(String orderNo) {
        try {
            LogisticsOrder order = logisticsOrderMapper.selectByOrderNo(orderNo);
            if (order == null) {
                return Result.error("订单不存在");
            }
            return Result.success(order);
        } catch (Exception e) {
            return Result.error("获取订单失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<Map<String, Object>>> listOrders() {
        try {
            List<LogisticsOrder> orders = logisticsOrderMapper.selectAll();
            List<Map<String, Object>> result = new ArrayList<>();
            
            for (LogisticsOrder order : orders) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", order.getId());
                map.put("orderNo", order.getOrderNo());
                map.put("senderName", order.getSenderName());
                map.put("senderPhone", order.getSenderPhone());
                map.put("receiverName", order.getReceiverName());
                map.put("receiverPhone", order.getReceiverPhone());
                map.put("receiverAddress", order.getReceiverAddress());
                map.put("status", order.getStatus());
                map.put("createTime", order.getCreateTime());
                result.add(map);
            }
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取订单列表失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<LogisticsOrder> updateOrder(LogisticsOrder order) {
        try {
            LogisticsOrder existingOrder = logisticsOrderMapper.selectById(order.getId());
            if (existingOrder == null) {
                return Result.error("订单不存在");
            }
            
            logisticsOrderMapper.update(order);
            return Result.success(order);
        } catch (Exception e) {
            return Result.error("更新订单失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> deleteOrder(Long id) {
        try {
            LogisticsOrder order = logisticsOrderMapper.selectById(id);
            if (order == null) {
                return Result.error("订单不存在");
            }
            
            logisticsOrderMapper.deleteById(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error("删除订单失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<LogisticsOrder> updateOrderStatus(Long id, String status) {
        try {
            LogisticsOrder order = logisticsOrderMapper.selectById(id);
            if (order == null) {
                return Result.error("订单不存在");
            }
            
            Integer statusCode = getStatusCode(status);
            if (statusCode == null) {
                return Result.error("无效的状态值");
            }
            
            logisticsOrderMapper.updateStatus(id, statusCode);
            order.setStatus(statusCode);
            return Result.success(order);
        } catch (Exception e) {
            return Result.error("更新订单状态失败：" + e.getMessage());
        }
    }

    @Override
    public Result<LogisticsOrder> getByOrderNo(String orderNo) {
        try {
            LogisticsOrder order = logisticsOrderMapper.selectByOrderNo(orderNo);
            if (order != null) {
                return Result.success(order);
            }
            if (orderNo.length() == 12) {
                order = logisticsOrderMapper.selectByOrderNo(orderNo.substring(0, 8) + "-" + orderNo.substring(8));
                if (order != null) {
                    return Result.success(order);
                }
            }
            return Result.error("订单不存在");
        } catch (Exception e) {
            return Result.error("获取订单失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<Map<String, Object>>> searchOrders(String orderNo, Integer status, String startDate, String endDate) {
        try {
            List<LogisticsOrder> orders = logisticsOrderMapper.search(orderNo, status, startDate, endDate);
            List<Map<String, Object>> result = new ArrayList<>();
            
            for (LogisticsOrder order : orders) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", order.getId());
                map.put("orderNo", order.getOrderNo());
                map.put("senderName", order.getSenderName());
                map.put("senderPhone", order.getSenderPhone());
                map.put("receiverName", order.getReceiverName());
                map.put("receiverPhone", order.getReceiverPhone());
                map.put("receiverAddress", order.getReceiverAddress());
                map.put("status", order.getStatus());
                map.put("createTime", order.getCreateTime());
                result.add(map);
            }
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("搜索订单失败：" + e.getMessage());
        }
    }

    // 生成订单号
    private String generateOrderNo() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 12);
    }

    // 获取状态文本
    private String getStatusText(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 0: return "待处理";
            case 1: return "运输中";
            case 2: return "已送达";
            case 3: return "已取消";
            default: return "未知";
        }
    }

    // 获取状态码
    private Integer getStatusCode(String status) {
        if (status == null) return null;
        switch (status) {
            case "待处理": return 0;
            case "运输中": return 1;
            case "已送达": return 2;
            case "已取消": return 3;
            default: return null;
        }
    }
} 